<script setup>
import { ref, computed, onMounted, onActivated, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router'
import { llmApi } from '@/utils/api'
import ChatWelcome from '@/components/chat/ChatWelcome.vue'
import ChatList from '@/components/chat/ChatList.vue'
import ChatInput from '@/components/chat/ChatInput.vue'

const route = useRoute()

const appTitle = '斌斌AI旅游策划师'
const appSubtitle = 'AI旅游小助手'

// 从localStorage获取用户信息
const userInfo = ref(null)

// 会话ID（后端用于记忆）：每次进入页面都生成新的
const sessionId = ref('')

function ensureSessionId() {
  // 每次进入页面都生成新的 sessionId
  const id = (crypto && crypto.randomUUID) ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
  sessionId.value = id
}

// 加载会话列表
async function loadSessionList() {
  if (!userInfo.value?.userId) {
    console.warn('用户ID不存在，无法加载会话列表')
    return
  }

  try {
    const response = await llmApi.getSession(userInfo.value.userId)

    // 处理响应数据（可能是包装在ResultVO中的）
    let sessionList = []
    if (Array.isArray(response)) {
      sessionList = response
    } else if (response && response.data && Array.isArray(response.data)) {
      sessionList = response.data
    } else if (response && Array.isArray(response.list)) {
      sessionList = response.list
    }

    // 转换格式并排序（最新的在前）
    historyItems.value = sessionList
      .map(session => ({
        id: session.sessionId,
        sessionId: session.sessionId,
        title: session.title || '新对话',
        time: formatServerTime(session.createTime),
        createTime: session.createTime
      }))
      .sort((a, b) => {
        // 按创建时间倒序排列
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
      })

    // 加载会话列表后，检查是否有保存的选中会话，如果有则自动加载
    const savedSelectedSessionId = localStorage.getItem('selected_session_id')
    if (savedSelectedSessionId) {
      // 检查该会话是否存在于列表中
      const exists = historyItems.value.some(item => item.sessionId === savedSelectedSessionId)
      if (exists) {
        // 恢复选中状态并加载对话记录
        await loadConversation(savedSelectedSessionId)
        return
      } else {
        // 如果会话不存在，清除保存的选中状态
        localStorage.removeItem('selected_session_id')
      }
    }
  } catch (error) {
    console.error('加载会话列表失败:', error)
  }
}

// 格式化服务器返回的时间
function formatServerTime(timeString) {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${month}/${day} ${hours}:${minutes}`
  } catch {
    return timeString
  }
}

// 加载对话记录
async function loadConversation(targetSessionId) {
  if (!targetSessionId) {
    console.warn('会话ID不存在，无法加载对话记录')
    return
  }

  try {
    isLoading.value = true
    const response = await llmApi.getConversation(targetSessionId)

    // 处理响应数据
    let conversationList = []
    if (Array.isArray(response)) {
      conversationList = response
    } else if (response && response.data && Array.isArray(response.data)) {
      conversationList = response.data
    } else if (response && Array.isArray(response.list)) {
      conversationList = response.list
    }

    // 转换为消息格式并按时间排序
    messages.value = conversationList
      .filter(conv => conv.role !== 'system') // 过滤掉 role 为 system 的消息
      .map(conv => ({
        id: conv.messageId || Date.now() + Math.random(),
        role: conv.role === 'user' ? 'user' : 'assistant',
        content: conv.message || '',
        isLoading: false,
        createdTime: conv.createdTime
      }))
      .sort((a, b) => {
        // 按创建时间升序排列（最早的在前）
        if (a.createdTime && b.createdTime) {
          return new Date(a.createdTime).getTime() - new Date(b.createdTime).getTime()
        }
        return 0
      })

    // 更新当前会话ID
    sessionId.value = targetSessionId
    currentSelectedSessionId.value = targetSessionId
    localStorage.setItem('chat_session_id', targetSessionId)
    // 保存选中的会话ID，用于刷新后恢复选中状态
    localStorage.setItem('selected_session_id', targetSessionId)

    // 更新当前会话标题
    const currentSession = historyItems.value.find(item => item.sessionId === targetSessionId)
    if (currentSession) {
      currentSessionTitle.value = currentSession.title
      currentSessionHistoryId.value = currentSession.id
    }
  } catch (error) {
    console.error('加载对话记录失败:', error)
    messages.value = []
  } finally {
    isLoading.value = false
  }
}

// 切换会话
async function switchSession(item) {
  // 如果点击的是当前会话，不重复加载
  if (currentSelectedSessionId.value === item.sessionId) {
    return
  }

  // 加载对话记录
  await loadConversation(item.sessionId)

  // 聚焦输入框
  setTimeout(() => {
    inputRef.value?.focus()
  }, 100)
}

// 初始化页面
function initPage() {
  // 从localStorage获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    try {
      userInfo.value = JSON.parse(storedUserInfo)
    } catch (error) {
      console.error('解析用户信息失败:', error)
    }
  }

  // 准备会话ID（用于新对话）
  ensureSessionId()

  // 加载会话列表
  loadSessionList()

  // 等待DOM更新后聚焦输入框和重置布局
  nextTick(() => {
    setTimeout(() => {
      inputRef.value?.focus()
      // 重置滚动位置
      window.scrollTo(0, 0)
      // 确保页面高度正确
      const pageElement = document.querySelector('.page')
      if (pageElement) {
        pageElement.style.height = '100vh'
      }
    }, 100)
  })
}

onMounted(() => {
  initPage()
})

// 当从其他页面切换回来时，重新初始化（如果使用 keep-alive）
onActivated(() => {
  initPage()
})

// 监听路由变化，确保从其他页面切换回来时能正确显示
watch(() => route.path, (newPath) => {
  if (newPath === '/chat') {
    nextTick(() => {
      initPage()
    })
  }
}, { immediate: false })

const historyItems = ref([])

const messages = ref([])

// 当前选中的会话ID
const currentSelectedSessionId = ref('')

// 判断是否有消息（是否进入聊天状态）
const hasMessages = computed(() => messages.value.length > 0)

// 加载状态
const isLoading = ref(false)

// 输入框引用
const inputRef = ref(null)

// 当前会话标题（用于判断是否已生成标题）
const currentSessionTitle = ref('')

// 当前会话在历史记录中的ID（用于更新标题）
const currentSessionHistoryId = ref(null)

// 格式化时间
function formatTime() {
  const now = new Date()
  const month = now.getMonth() + 1
  const day = now.getDate()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${month}/${day} ${hours}:${minutes}`
}

// 生成并更新标题
async function generateAndUpdateTitle(userMessage) {
  try {
    // 获取 userId
    const userId = userInfo.value?.userId || 0
    let response = await llmApi.generateTitle(userMessage, userId)

    // 如果后端返回的是 JSON 字符串（而不是对象），先解析它
    if (typeof response === 'string')
        response = JSON.parse(response)

    let title = ''

    if (response && response.choices && response.choices.length > 0) {
      const messageContent = response.choices[0].message?.content
      if (messageContent) {
        title = messageContent.trim()
      }
    }

    if (title) {
      currentSessionTitle.value = title

      // 更新历史记录中的标题
      if (currentSessionHistoryId.value) {
        const historyItem = historyItems.value.find(item => item.id === currentSessionHistoryId.value)
        if (historyItem) {
          historyItem.title = title
        }
      }
    }
  } catch (error) {
    console.error('生成标题失败:', error)
  }
}

async function handleSend(text) {
  // 如果是新对话且没有会话记录，创建新的会话项
  if (messages.value.length === 0 && !currentSelectedSessionId.value) {
    const historyId = sessionId.value
    currentSessionHistoryId.value = historyId
    historyItems.value.unshift({
      id: historyId,
      title: '新对话',
      time: formatTime(),
      sessionId: sessionId.value,
      createTime: new Date().toISOString()
    })
    currentSelectedSessionId.value = sessionId.value
  }

  // 添加用户消息
  const userMessage = { id: Date.now(), role: 'user', content: text }
  messages.value.push(userMessage)

  // 添加AI消息（初始为空）
  const aiMessageId = Date.now() + 1
  const aiMessage = {
    id: aiMessageId,
    role: 'assistant',
    content: '',
    isLoading: true
  }
  messages.value.push(aiMessage)

  isLoading.value = true

  try {
    // 获取 userId（
    const userId = userInfo.value?.userId || 0
    llmApi.chatStream(
      sessionId.value,
      text,
      userId,
      // onMessage: 每次接收到数据块时调用
      (chunk) => {
        const messageIndex = messages.value.findIndex(m => m.id === aiMessageId)
        if (messageIndex !== -1) {
          messages.value[messageIndex].content += chunk

          messages.value[messageIndex].isLoading = false
        }
      },
      // onComplete: 流式传输完成
      () => {
        const messageIndex = messages.value.findIndex(m => m.id === aiMessageId)
        if (messageIndex !== -1) {
          messages.value[messageIndex].isLoading = false
        }
        isLoading.value = false

        // 如果是第一次输出（还没有标题），则生成标题
        if (!currentSessionTitle.value && messages.value.length === 2) {
          generateAndUpdateTitle(text)
        }
      }
    )
  } catch (error) {
    console.error('❌ 调用失败:', error)


    isLoading.value = false
  }
}

// 侧边栏收起/展开
const isSidebarCollapsed = ref(false)
function toggleSidebar() {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
}

// 开始新对话
function startNewChat() {
  // 清空消息
  messages.value = []

  // 重置会话状态
  currentSessionTitle.value = ''
  currentSessionHistoryId.value = null
  currentSelectedSessionId.value = ''
  isLoading.value = false

  // 清除保存的选中会话
  localStorage.removeItem('selected_session_id')

  // 生成新的会话ID
  const newSessionId = (crypto && crypto.randomUUID)
    ? crypto.randomUUID()
    : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
  sessionId.value = newSessionId
  localStorage.setItem('chat_session_id', newSessionId)

  // 聚焦输入框
  setTimeout(() => {
    inputRef.value?.focus()
  }, 100)
}
</script>

<template>
  <div class="page" :class="{ 'collapsed': isSidebarCollapsed }">
    <aside class="sidebar">
      <div class="sidebar-inner">
        <div class="sidebar-header">
          <span class="sidebar-title">对话历史</span>
          <button
            v-if="!isSidebarCollapsed"
            class="sidebar-pin"
            @click="toggleSidebar"
          >收起</button>
        </div>

        <!-- 新对话按钮 -->
        <button v-show="!isSidebarCollapsed" class="new-chat-btn" @click="startNewChat">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 5V19M5 12H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
          <span>新对话</span>
        </button>

        <div v-if="isSidebarCollapsed" class="collapse-actions">
          <button class="sidebar-pin" @click="toggleSidebar">展开</button>
          <button class="new-chat-btn-mini" @click="startNewChat" title="新对话">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 5V19M5 12H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </button>
        </div>

        <ul v-show="!isSidebarCollapsed" class="history-list">
          <li
            v-for="item in historyItems"
            :key="item.id"
            class="history-item"
            :class="{ 'active': currentSelectedSessionId === item.sessionId }"
            @click="switchSession(item)"
          >
            <div class="history-title">{{ item.title }}</div>
            <div class="history-time">{{ item.time }}</div>
          </li>
        </ul>

        <div class="sidebar-spacer"></div>
      </div>
    </aside>

    <main class="main">
      <!-- 欢迎页面 - 新对话时显示 -->
      <ChatWelcome
        v-if="!hasMessages"
        :title="appTitle"
        :subtitle="appSubtitle"
      />

      <!-- 聊天列表 - 有消息时显示 -->
      <ChatList
        v-else
        :messages="messages"
        :user-info="userInfo"
      />

      <!-- 输入框 - 始终显示 -->
      <ChatInput
        ref="inputRef"
        :is-loading="isLoading"
        @send="handleSend"
      />
    </main>
  </div>
</template>

<style scoped>
:global(html, body, #app) {
  height: 100%;
  overflow: hidden;
  margin: 0;
  height: calc(100vh - 64px);
}

.page {
  display: grid;
  grid-template-columns: 280px 1fr;
  height: calc(100vh - 64px);
  background: #ffffff;
}

.page.collapsed {
  grid-template-columns: 72px 1fr;
}

.sidebar {
  background: #ffffff;
  border-right: 1px solid #eef0f5;
  height: calc(100vh - 64px);
  padding-top: 64px;
}

.sidebar-inner {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 64px);
  padding: 16px 16px 0 16px;
  position: relative;
  overflow-y: auto;
}

.sidebar-spacer {
  flex: 1 1 auto;
}

.collapse-actions {
  margin-bottom: 12px;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.sidebar-title {
  font-weight: 600;
  color: #2b2f36;
}

.sidebar-pin {
  border: none;
  background: #f2f4f8;
  color: #5b6b8b;
  padding: 6px 10px;
  border-radius: 8px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.2s ease;
}

.sidebar-pin:hover {
  background: #e5e7eb;
}

.page.collapsed .sidebar-pin {
  width: 100%;
}

/* 新对话按钮 */
.new-chat-btn {
  width: 100%;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  padding: 12px 16px;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 16px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.new-chat-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.new-chat-btn:active {
  transform: translateY(0);
}

.new-chat-btn svg {
  width: 18px;
  height: 18px;
}

/* 新对话按钮（收起状态） */
.new-chat-btn-mini {
  width: 100%;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  transition: all 0.2s ease;
}

.new-chat-btn-mini:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.new-chat-btn-mini svg {
  width: 20px;
  height: 20px;
}

.history-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.history-item {
  background: #fbfcff;
  border: 1px solid #eef0f5;
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.history-item:hover {
  background: #f0f2f5;
  border-color: #d0d5dd;
}

.history-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: #ffffff;
}

.history-item.active .history-title {
  color: #ffffff;
}

.history-item.active .history-time {
  color: rgba(255, 255, 255, 0.8);
}

.history-title {
  color: #2b2f36;
  font-size: 14px;
  margin-bottom: 6px;
}

.history-time {
  color: #98a2b3;
  font-size: 12px;
}

.main {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  overflow: hidden;
}
</style>
